import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QSplitter, QTextEdit, QToolBar, QAction, QFileDialog,
                             QMessageBox, QLabel, QStatusBar)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtGui import QTextDocument
from util.markdownHandler import MarkdownHandler  # 导入MarkdownHandler


class MarkdownEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("现代化Markdown编辑器")
        self.setGeometry(100, 100, 1200, 800)

        self.current_file = None
        self.markdown_handler = MarkdownHandler()  # 创建MarkdownHandler实例
        self.setup_statusbar()  # 先初始化状态栏
        self.setup_ui()  # 然后初始化UI
        self.setup_toolbar()  # 最后初始化工具栏

        # 自动保存计时器
        self.autosave_timer = QTimer()
        self.autosave_timer.timeout.connect(self.autosave_check)
        self.autosave_timer.start(30000)  # 30秒检查一次

    def setup_ui(self):
        """设置主界面布局"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)

        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)

        # 左侧编辑器
        self.editor = QTextEdit()
        self.editor.setStyleSheet("""
            QTextEdit {
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 14px;
                line-height: 1.5;
                padding: 10px;
            }
        """)
        self.editor.textChanged.connect(self.update_preview)

        # 右侧预览
        self.preview = QWebEngineView()
        self.preview.setStyleSheet("background-color: white;")

        splitter.addWidget(self.editor)
        splitter.addWidget(self.preview)
        splitter.setSizes([400, 400])

        main_layout.addWidget(splitter)

        # 初始空白文档
        self.new_document()

    def setup_statusbar(self):
        """设置状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)

        self.file_status = QLabel("未保存的文档")
        self.status_bar.addWidget(self.file_status)

    def setup_toolbar(self):
        """设置工具栏"""
        toolbar = QToolBar("主工具栏")
        toolbar.setMovable(False)
        self.addToolBar(toolbar)

        # 新建
        new_action = QAction("新建", self)
        new_action.setShortcut("Ctrl+N")
        new_action.triggered.connect(self.new_document)
        toolbar.addAction(new_action)

        # 打开
        open_action = QAction("打开", self)
        open_action.setShortcut("Ctrl+O")
        open_action.triggered.connect(self.open_file)
        toolbar.addAction(open_action)

        # 保存
        save_action = QAction("保存", self)
        save_action.setShortcut("Ctrl+S")
        save_action.triggered.connect(self.save_file)
        toolbar.addAction(save_action)

        # 另存为
        save_as_action = QAction("另存为", self)
        save_as_action.setShortcut("Ctrl+Shift+S")
        save_as_action.triggered.connect(self.save_file_as)
        toolbar.addAction(save_as_action)

        toolbar.addSeparator()

        # 导出PDF
        export_pdf_action = QAction("导出PDF", self)
        export_pdf_action.setShortcut("Ctrl+P")
        export_pdf_action.triggered.connect(self.export_to_pdf)
        toolbar.addAction(export_pdf_action)

    def new_document(self):
        """新建文档"""
        self.editor.clear()
        self.current_file = None
        self.update_status("未保存的文档")
        self.update_preview()

    def open_file(self):
        """打开文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "打开Markdown文件", "",
            "Markdown文件 (*.md *.markdown);;所有文件 (*.*)"
        )

        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    self.editor.setPlainText(content)
                    self.current_file = file_path
                    self.update_status(file_path)
                    self.update_preview()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法打开文件: {str(e)}")

    def save_file(self):
        """保存文件"""
        if self.current_file:
            self._save_to_file(self.current_file)
        else:
            self.save_file_as()

    def save_file_as(self):
        """另存为文件"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存Markdown文件", "",
            "Markdown文件 (*.md *.markdown);;所有文件 (*.*)"
        )

        if file_path:
            # 确保文件有.md扩展名
            if not file_path.lower().endswith(('.md', '.markdown')):
                file_path += '.md'

            self._save_to_file(file_path)
            self.current_file = file_path
            self.update_status(file_path)

    def _save_to_file(self, file_path):
        """实际保存文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(self.editor.toPlainText())
            self.update_status(file_path)
            return True
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存文件失败: {str(e)}")
            return False

    def export_to_pdf(self):
        """导出为PDF"""
        if not self.editor.toPlainText().strip():
            QMessageBox.warning(self, "警告", "文档内容为空，无法导出PDF")
            return

        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出PDF", "", "PDF文件 (*.pdf)"
        )

        if file_path:
            # 确保文件有.pdf扩展名
            if not file_path.lower().endswith('.pdf'):
                file_path += '.pdf'

            # 创建打印机
            printer = QPrinter(QPrinter.HighResolution)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(file_path)

            # 设置页边距（毫米）
            printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter)

            # 创建HTML文档
            html = self._generate_html()

            # 使用WebEngineView打印
            web_view = QWebEngineView()
            web_view.setHtml(html)

            def print_loaded(ok):
                if ok:
                    web_view.page().print(printer, lambda success: QMessageBox.information(
                        self, "导出成功" if success else "导出失败",
                        f"PDF已保存到: {file_path}" if success else "导出PDF失败"
                    ))
                else:
                    QMessageBox.critical(self, "错误", "无法加载HTML内容")

            web_view.loadFinished.connect(print_loaded)

    def _generate_html(self):
        """使用MarkdownHandler生成HTML内容"""
        markdown_text = self.editor.toPlainText()
        return self.markdown_handler.convert_to_html(markdown_text)

    def update_preview(self):
        """更新预览"""
        markdown_text = self.editor.toPlainText()
        html_content = self._generate_html()
        self.preview.setHtml(html_content)


    def update_status(self, message):
        """更新状态栏"""
        self.file_status.setText(message)

    def autosave_check(self):
        """自动保存检查"""
        if self.current_file and self.editor.document().isModified():
            if self._save_to_file(self.current_file):
                self.status_bar.showMessage(f"自动保存成功: {self.current_file}", 3000)

    def closeEvent(self, event):
        """关闭前检查未保存的更改"""
        if self.editor.document().isModified():
            reply = QMessageBox.question(
                self, '未保存的更改',
                '文档有未保存的更改，是否保存?',
                QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,
                QMessageBox.Save
            )

            if reply == QMessageBox.Save:
                if not self.save_file():
                    event.ignore()
                    return
            elif reply == QMessageBox.Cancel:
                event.ignore()
                return

        event.accept()


if __name__ == "__main__":
    app = QApplication([])
    app.setStyle("Fusion")  # 现代化外观

    editor = MarkdownEditor()
    editor.show()

    app.exec_()